package com.ecotope.quartz.module.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ecotope.quartz.module.dao.AtmosphericStationDao;
import com.ecotope.quartz.module.entity.AccessData;
import com.ecotope.quartz.module.entity.AtmosphericStation;
import com.ecotope.quartz.module.opentsdb.ExpectResponse;
import com.ecotope.quartz.module.opentsdb.HttpClientImpl;
import com.ecotope.quartz.module.opentsdb.builder.MetricBuilder;
import com.ecotope.quartz.module.opentsdb.response.Response;
import com.ecotope.quartz.module.service.AccessDataService;
import com.ecotope.quartz.module.service.AtmosphericStationService;
import com.ecotope.quartz.module.util.HttpURLConnectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author JK
 */
@Service
public class AtmosphericStationImpl implements AtmosphericStationService {

    private static final Logger log = LoggerFactory.getLogger(AtmosphericStationService.class);

    //省平台地址
    private String baseUrl = "http://59.202.42.88:8180/sjmh/dynamicservice/dynamicquery";

    //页大小
    private Integer pageSize = 10000;

    //QX
    private String fwxhQx = "f9fa13d4b3f2411fac31cb0c38de39a9";
    private String keyQx = "e2fccde6-40de-4743-be59-01eafe539238";

    //PJ
    private String fwxhPj = "1fb0c439409e4d5e9e20a9be146c6a1b";
    private String keyPj = "e7fbac54-f7ef-4004-b9d3-9dec0e066284";

    @Autowired
    private AtmosphericStationDao atmosphericStationDao;
    @Autowired
    private AccessDataService accessDataService;

    @Override
    public List<AtmosphericStation> selectList(AtmosphericStation atmosphericStation) {
        return atmosphericStationDao.selectList(atmosphericStation);
    }

    @Override
    public int insert(AtmosphericStation atmosphericStation) {
        return atmosphericStationDao.insert(atmosphericStation);
    }

    @Override
    public void insertQX() throws ParseException {
        Integer pageNum = 4;

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//        Date date = new Date();
        Date date = df.parse("2020-12-30");
        String JSSJ = df.format(date);

        Date dateNew = date;
        Calendar calendarNew = Calendar.getInstance();
        calendarNew.setTime(dateNew);
        calendarNew.add(Calendar.MONTH, -3);
        dateNew = calendarNew.getTime();
        String KSSJ = df.format(dateNew);
        log.info("QX----------------insertThreeMonthQX()");

        HttpClientImpl client = new HttpClientImpl("http://61.164.218.155:61242");
        for (int i = 1; i < 10000; i++) {
            //空气质量站点请求地址——省平台
            String url = baseUrl + "?fwxh=" + fwxhQx + "&key=" + keyQx + "&pagenum=" + pageNum + "&pageSize=" + pageSize + "&KSSJ=" + KSSJ + "&JSSJ=" + JSSJ;
            try {

                String methodReturn = HttpURLConnectionUtil.getMethod(url);
                if (HttpURLConnectionUtil.isJsonObject(methodReturn)) {
                    JSONObject jsonObject = JSONObject.parseObject(methodReturn);
                    JSONObject data = jsonObject.getJSONObject("data");
                    String qxkqzdxssj = data.getString("QXKQZDXSSJ");
                    //mysql数据库 记录数据插入时间
                    AccessData accessData = AccessData.builder().type(3).url(url).data("QX").build();
                    accessDataService.insert(accessData);
                    log.info("存入qx-mysql数据：" + url);
                    if (qxkqzdxssj != null && !qxkqzdxssj.equals("[]")) {
                        //插入opentsdb
                        JSONArray jsonArray = JSONArray.parseArray(qxkqzdxssj);
                        log.info("存入qx-opentsdb开始---------");

                        for (Object o : jsonArray) {
                            Map map = JSONObject.parseObject(o.toString(), Map.class);
                            //移除不必要的数据
                            map.remove("CJSJ");
                            map.remove("XGSJ");
                            map.remove("XH");

                            //数据标记
                            SJBJMap(map);
                            //因子代码
                            YZBHMap(map);

                            //转换时间戳
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            if (map.get("JCSJ") != null) {
                                long timestamp = sdf.parse(String.valueOf(map.get("JCSJ"))).getTime();
                                String host = String.valueOf(map.get("ZDBH"));
                                MetricBuilder builder = MetricBuilder.getInstance();
                                map.remove("JCSJ");
                                map.remove("ZDBH");
                                for (Object entry : map.entrySet()) {
                                    Map.Entry<String, Object> map1 = (Map.Entry<String, Object>) entry;
                                    Double value = null;
                                    if ("--".equals(map1.getValue())) {
                                        value = 0.0;
                                    } else {
                                        value = Double.parseDouble(String.valueOf(map1.getValue()));
                                    }
                                    builder.addMetric("mete.air").setDataPoint(timestamp, value).addTag("host", host).addTag("index", map1.getKey().toLowerCase());
                                }
                                //存入opentsdb
                                Response response = client.pushMetrics(builder,
                                        ExpectResponse.SUMMARY);
                                if (!response.isSuccess()) {
                                    log.info("插入opentsdb数据失败");
                                }
                            }
                        }
                        log.info("存入qx-opentsdb数据结束");
                        pageNum++;
                    } else {
                        JSSJ = KSSJ;
                        Date dateNewFor = df.parse(JSSJ);
                        Calendar calendarNewFor = Calendar.getInstance();
                        calendarNewFor.setTime(dateNewFor);
                        calendarNewFor.add(Calendar.MONTH, -3);
                        dateNewFor = calendarNewFor.getTime();
                        KSSJ = df.format(dateNewFor);
                        pageNum = 1;

                        log.info("----------KSSJ:------" + KSSJ);
                        Calendar c = Calendar.getInstance();
                        c.setTime(df.parse("2018-01-01"));
                        if (c.compareTo(calendarNewFor) == 1) {
                            break;
                        }
                    }
                } else {
                    Thread.sleep(1000 * 60 * 5);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void insertPJ() throws ParseException {
        log.info("Pj-------insertThreeMonthPJ()");
        Integer pageNum = 2;

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//        Date date = new Date();
        Date date = df.parse("2020-12-29");
        String JSSJ = df.format(date);

        Date dateNew = date;
        Calendar calendarNew = Calendar.getInstance();
        calendarNew.setTime(dateNew);
        calendarNew.add(Calendar.MONTH, -3);
        dateNew = calendarNew.getTime();
        String KSSJ = df.format(dateNew);

        HttpClientImpl client = new HttpClientImpl("http://61.164.218.155:61242");
        for (int i = 1; i < 10000; i++) {
            //空气质量站点请求地址——省平台
            String url = baseUrl + "?fwxh=" + fwxhPj + "&key=" + keyPj + "&pagenum=" + pageNum + "&pageSize=" + pageSize + "&KSSJ=" + KSSJ + "&JSSJ=" + JSSJ;
            try {

                String methodReturn = HttpURLConnectionUtil.getMethod(url);
                if (HttpURLConnectionUtil.isJsonObject(methodReturn)) {
                    JSONObject jsonObject = JSONObject.parseObject(methodReturn);
                    JSONObject data = jsonObject.getJSONObject("data");
                    String qxkqzdxssj = data.getString("QXKQZDXSSJPJ");

                    //mysql数据库 记录数据插入时间
                    AccessData accessData = AccessData.builder().type(4).url(url).data("PJ").build();
                    accessDataService.insert(accessData);
                    log.info("存入pj-mysql数据：" + url);

                    if (qxkqzdxssj != null && !qxkqzdxssj.equals("[]")) {
                        log.info("存入pj-opentsdb数据开始");
                        //插入opentsdb
                        JSONArray jsonArray = JSONArray.parseArray(qxkqzdxssj);
                        for (Object o : jsonArray) {
                            Map map = JSONObject.parseObject(o.toString(), Map.class);

                            //移除不必要的数据
                            map.remove("CJSJ");
                            map.remove("XGSJ");
                            map.remove("XH");
                            map.remove("BZ");

                            //评价等级
                            PJDJMap(map);

                            //转换时间戳
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            if (map.get("PJSJ") != null) {
                                long timestamp = sdf.parse(String.valueOf(map.get("PJSJ"))).getTime();
                                String host = String.valueOf(map.get("ZDBH"));
                                MetricBuilder builder = MetricBuilder.getInstance();
                                map.remove("PJSJ");
                                map.remove("ZDBH");
                                for (Object entry : map.entrySet()) {
                                    Map.Entry<String, Object> map1 = (Map.Entry<String, Object>) entry;
                                    Double value = null;
                                    if ("--".equals(map1.getValue())) {
                                        value = 0.0;
                                    } else {
                                        value = Double.parseDouble(String.valueOf(map1.getValue()));
                                    }
                                    builder.addMetric("mete.air").setDataPoint(timestamp, value).addTag("host", host).addTag("index", map1.getKey().toLowerCase());
                                }
                                //存入opentsdb
                                Response response = client.pushMetrics(builder,
                                        ExpectResponse.SUMMARY);
                                if (!response.isSuccess()) {
                                    log.info("插入opentsdb数据失败");
                                }
                            }
                        }
                        log.info("存入pj-opentsdb数据结束");
                    } else {
                        JSSJ = KSSJ;
                        Date dateNewFor = df.parse(JSSJ);
                        Calendar calendarNewFor = Calendar.getInstance();
                        calendarNewFor.setTime(dateNewFor);
                        calendarNewFor.add(Calendar.MONTH, -3);
                        dateNewFor = calendarNewFor.getTime();
                        KSSJ = df.format(dateNewFor);
                        pageNum = 1;

                        log.info("----------KSSJ:------" + KSSJ);
                        Calendar c = Calendar.getInstance();
                        c.setTime(df.parse("2018-01-01"));
                        if (c.compareTo(calendarNewFor) == 1) {
                            break;
                        }
                    }
                } else {
                    Thread.sleep(1000 * 60 * 5);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }


    /**
     * 数据标记 1:"有效";2:"连续数";3:"有效数据不足";4:"其他"
     */
    private Map SJBJMap(Map map) {

        if (map.get("SJBJ") != null) {
            String sjbj = String.valueOf(map.get("SJBJ"));
            map.remove("SJBJ");
            //数据标记 1:"有效";2:"连续数";3:"有效数据不足";4:"其他"
            switch (sjbj) {
                case "有效":
                    map.put("SJBJ", 1);
                    break;
                case "连续数":
                    map.put("SJBJ", 2);
                    break;
                case "有效数据不足":
                    map.put("SJBJ", 3);
                    break;
                default:
                    map.put("SJBJ", 4);
                    break;
            }
        }
        return map;
    }

    /**
     * 因子代码 1:"COL1";2:"COL2";3:"COL3"；4:"COL4"；5:"COL5"；6:"COL6"；7:"COL7"；8:"COL8"；9:"COL9"；10:"COL10"；11:其他；
     */
    private Map YZBHMap(Map map) {

        if (map.get("YZBH") != null) {
            String yzbh = String.valueOf(map.get("YZBH"));
            map.remove("YZBH");
            //因子代码 1:"COL1";2:"COL2";3:"COL3"；4:"COL4"；5:"COL5"；6:"COL6"；7:"COL7"；8:"COL8"；9:"COL9"；10:"COL10"；11:其他；
            switch (yzbh) {
                case "COL1":
                    map.put("YZBH", 1);
                    break;
                case "COL2":
                    map.put("YZBH", 2);
                    break;
                case "COL3":
                    map.put("YZBH", 3);
                    break;
                case "COL4":
                    map.put("YZBH", 4);
                    break;
                case "COL5":
                    map.put("YZBH", 5);
                    break;
                case "COL6":
                    map.put("YZBH", 6);
                    break;
                case "COL7":
                    map.put("YZBH", 7);
                    break;
                case "COL8":
                    map.put("YZBH", 8);
                    break;
                case "COL9":
                    map.put("YZBH", 9);
                    break;
                case "COL10":
                    map.put("YZBH", 10);
                    break;
                default:
                    map.put("YZBH", 11);
                    break;
            }
        }
        return map;
    }

    /**
     * 评价等级  1："Ⅰ"；2："Ⅱ"；3："Ⅲ"；4："Ⅳ"；0："--"
     *
     * @param map
     * @return
     */
    private Map PJDJMap(Map map) {

        if (map.get("PJDJ") != null) {
            String pjdj = String.valueOf(map.get("PJDJ"));
            map.remove("PJDJ");
            //评价等级  1："Ⅰ"；2："Ⅱ"；3："Ⅲ"；4："Ⅳ"；0："--"
            switch (pjdj) {
                case "--":
                    map.put("PJDJ", 0);
                    break;
                case "Ⅰ":
                    map.put("PJDJ", 1);
                    break;
                case "Ⅱ":
                    map.put("PJDJ", 2);
                    break;
                case "Ⅲ":
                    map.put("PJDJ", 3);
                    break;
                case "Ⅳ":
                    map.put("PJDJ", 4);
                    break;
                default:
                    map.put("PJDJ", 5);
                    break;
            }
        }
        return map;
    }
}
